package com.ccloud.auth.modules.controller;

import cn.hutool.core.util.RandomUtil;
import com.ccloud.common.redis.cache.ZCache;
import com.ccloud.common.core.reqres.response.Result;
import com.ccloud.common.core.utils.RandImageUtil;
import com.ccloud.api.system.model.SysLoginModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author chentl
 */
@Api(tags = "验证码接口")
@RequestMapping("/oauth/captcha")
@RestController
@Slf4j
public class CaptchaController {

    @Resource
    private ZCache zCache;

    /**
     * 后台生成图形验证码 ：有效
     *
     * @param key String
     * @return Result<Object>
     */
    @ApiOperation("获取验证码")
    @GetMapping(value = "/randomImage/{key}")
    public Result<Object> randomImage(@PathVariable String key) {
        Result<Object> res;
        try {
            String code = RandomUtil.randomString(4);
            String lowerCaseCode = code.toLowerCase();
            String realKey = DigestUtils.md5DigestAsHex((lowerCaseCode + key).getBytes());
            zCache.put(realKey, lowerCaseCode, 60 * 1000);
            String base64 = RandImageUtil.generate(code);
            res = Result.ok();
            res.setResult(base64);
        } catch (Exception e) {
            res = Result.error("获取验证码出错");
            log.error("获取验证码出错", e);
        }
        return res;
    }

    /**
     * 图形验证码
     *
     * @param sysLoginModel SysLoginModel
     * @return Result<?>
     */
    @RequestMapping(value = "/checkCaptcha", method = RequestMethod.POST)
    public Result<?> checkCaptcha(@RequestBody SysLoginModel sysLoginModel) {
        String captcha = sysLoginModel.captcha();
        String checkKey = sysLoginModel.checkKey();
        if (captcha == null) {
            return Result.error("验证码无效");
        }
        String lowerCaseCaptcha = captcha.toLowerCase();
        String realKey = DigestUtils.md5DigestAsHex((lowerCaseCaptcha + checkKey).getBytes());
        Object checkCode = zCache.get(realKey, String.class);
        if (checkCode == null || !checkCode.equals(lowerCaseCaptcha)) {
            return Result.error("验证码错误");
        }
        return Result.ok();
    }


}
